<template>
	<div>
		<a-card :borderd="false" class="mb-2">
			<a-row :gutter="6">
				<a-col :span="2">
					<a-select v-model:value="config.listQuery.userId" style="width: 100%" placeholder="请选择用户"
							  filterable allowClear>
						<a-select-option v-for="item in config.userList" :key="item.name" :value="item.id">
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-col>

				<a-col :span="2">
					<a-select v-model:value="config.listQuery.licenseId" style="width: 100%" placeholder="请选择license"
							  allowClear>
						<a-select-option v-for="item in config.licenseList" :key="item.key"
										 :value="item.id">{{ item.name }}
						</a-select-option>
					</a-select>
				</a-col>

				<a-col :span="2">
					<a-select v-model:value="config.listQuery.protocal" style="width: 100%" placeholder="请选择协议"
							  allowClear>
						<a-select-option v-for="item in config.protocalList" :key="item.name"
										 :value="item.name"
										 :disabled="!item.enable">{{ item.name }}
						</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="2">
					<a-input v-model:value="config.listQuery.serverPort"
							 placeholder="请输入服务端端口" :maxlength="5" show-word-limit/>
				</a-col>
				<a-col :span="2">
					<a-select v-model:value="config.listQuery.isOnline" style="width:100%" placeholder="请选择在线状态"
							  clearable>
						<a-select-option v-for="item in config.selectObj.onlineOptions" :key="item.value"
										 :value="item.value">{{ item.label }}
						</a-select-option>
					</a-select>
				</a-col>

				<a-col :span="2">
					<a-select v-model:value="config.listQuery.enable" style="width: 100%;" placeholder="请选择启用状态"
							  clearable
					>
						<a-select-option v-for="item in config.selectObj.statusOptions" :key="item.value"
										 :value="item.value">{{ item.label }}
						</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="2">
					<a-input v-model:value="config.listQuery.description"
							 placeholder="请输入描述详情" show-word-limit/>
				</a-col>
				<a-col :span="2">
					<a-space>
						<a-button @click="tableRef.refresh()">搜索</a-button>
						<a-button @click="handleCreate" type="primary">新增</a-button>
					</a-space>
				</a-col>

				<a-col :span="4">
						<a-button @click="openPort">开通端口</a-button>
				</a-col>



			</a-row>
		</a-card>


		<a-card>
			<h-table :paged="true" ref="tableRef" :data="getList" :columns="columns">
			</h-table>

		</a-card>

		<a-modal v-model:open="config.dialogFormVisible" :destroyOnClose="true" :width="1000" :closable="false"
				 @cancel="config.dialogFormVisible = false" @ok="saveData">
			<a-form :rules="config.rules" ref="dataForm" :model="config.temp">
				<a-form-item label="License" name="licenseId">

					<a-select @change="selectedFeeItem" v-model:value="config.temp.licenseId"
							  placeholder="请选择license" allow-clear>
						<a-select-option v-for="item in config.licenseAuthList" :key="item.key"
										 :value="item.id">{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="协议" name="protocal">
					<a-select v-model:value="config.temp.protocal" placeholder="请选择">
						<a-select-option v-for="item in config.protocalList" :key="item.name" :value="item.name"
										 :disabled="!item.enable">
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="服务端端口" name="serverPort">
					<load-select style="width: 280px;"
								 v-model="config.temp.serverPort"
								 :data="config.serverPortList"
								 :page="config.loadServerPortQuery.page"
								 :hasMore="config.more"
								 :clearable="false"
								 :dictLabel="'port'"
								 :dictValue="'port'"
								 :request="loadServerPort"/>
				</a-form-item>
				<a-form-item label="客户端IP" name="clientIp">
					<a-input v-model:value="config.temp.clientIp"></a-input>
				</a-form-item>
				<a-form-item label="客户端端口" name="clientPort">
					<a-input v-model:value="config.temp.clientPort"></a-input>
				</a-form-item>
				<a-form-item label="域名" name="subdomain"
							 v-if="(config.temp.protocal === 'HTTP' || config.temp.protocal === 'HTTP(S)') && config.domainName && config.domainName != ''">
					<a-input v-model:value="config.temp.subdomain">
						<template slot="append">.{{ config.domainName }}</template>
					</a-input>
				</a-form-item>
				<a-form-item label="响应数量" name="proxyResponses" v-if="config.temp.protocal === 'UDP'">
					<a-input v-model:value="config.temp.proxyResponses"></a-input>
				</a-form-item>
				<a-form-item label="超时时间" name="proxyTimeoutMs" v-if="config.temp.protocal === 'UDP'">
					<a-input v-model:value="config.temp.proxyTimeoutMs">
						<template slot="append">毫秒</template>
					</a-input>
				</a-form-item>
				<a-form-item label="安全组" name="securityGroup">
					<a-select v-model:value="config.temp.securityGroupId" allow-clear>
						<a-select-option v-for="item in config.securityGroupList" :key="item.id" :value="item.id">
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="上传限速" name="upLimitRate">
					<a-input v-model:value="config.temp.upLimitRate" placeholder="如：10240B、500K、1M"></a-input>
				</a-form-item>
				<a-form-item label="下载限速" name="downLimitRate">
					<a-input v-model:value="config.temp.downLimitRate" placeholder="如：10240B、500K、1M"></a-input>
				</a-form-item>
				<a-form-item label="描述" name="description">
					<a-input v-model:value="config.temp.description"></a-input>
				</a-form-item>
			</a-form>

		</a-modal>

		<a-modal v-model:open="config.dialogPvVisible" :destroyOnClose="true" :width="1000" :closable="false"
				 @cancel="config.dialogPvVisible = false" @ok="config.dialogPvVisible = false">
			<el-table :data="config.pvData" border fit highlight-current-row style="width: 100%">
				<el-table-column prop="key" label="Channel"></el-table-column>
				<el-table-column prop="pv" label="Pv"></el-table-column>
			</el-table>
		</a-modal>

	</div>
</template>

<script setup>
import portMappingApi from '@/api/portMapping/portMappingApi'
import securityGroupApi from '@/api/securityGroup/securityGroupApi'
import portPoolApi from '@/api/portPool/portPoolApi'
import licenseApi from '@/api/license/licenseApi'
import protocalApi from '@/api/protocal/protocalApi'
import userApi from '@/api/sys/userApi'
import domainApi from '@/api/domain/domainApi'
// 下拉选择加载组件
import tool from '@/utils/tool'
import {message} from 'ant-design-vue'
import loadSelect from "@/components/Select/SelectLoadMore.vue";


const tableRef = ref()
const dataForm = ref()
const config = ref({
	tableKey: 0,
	list: null,
	total: null,
	listLoading: true,
	listQuery: {
		importance: undefined,
		title: undefined,
		type: undefined,
		userId: undefined,
		license: undefined,
		port: undefined,
		isOnline: undefined,
		enable: undefined,
		description: undefined

	},
	importanceOptions: [1, 2, 3],
	userList: [],
	licenseList: [],
	protocalList: [],
	licenseAuthList: [],
	serverPortList: [],
	domainName: '',
	showReviewer: false,
	temp: {
		id: undefined,
		licenseId: undefined,
		licenseName: undefined,
		serverPort: undefined,
		clientIp: undefined,
		clientPort: undefined,
		protocal: undefined,
		proxyResponses: undefined,
		proxyTimeoutMs: undefined
	},
	selectObj: {
		statusOptions: [{label: '启用', value: 1}, {label: '禁用', value: 2}],
		onlineOptions: [{label: '在线', value: 1}, {label: '离线', value: 2}]
	},
	dialogFormVisible: false,
	dialogStatus: '',
	textMap: {
		update: '编辑',
		create: '新建'
	},
	dialogPvVisible: false,
	pvData: [],
	rules: {
		licenseId: [{required: true, message: '请选择License', trigger: 'blur,change'}],
		serverPort: [{required: true, message: '请输入服务端端口', trigger: 'blur'},
			// { validator: isPortAvailable, trigger: 'change' }
		],
		clientIp: [{required: true, message: '请输入客户端IP', trigger: 'blur'}],
		clientPort: [{required: true, message: '请输入客户端端口', trigger: 'blur'}],
		protocal: [{required: true, message: '请选择协议', trigger: 'blur'}]
	},
	downloadLoading: false,
	countryColumns: [
		{prop: 'userName', label: '用户名', align: 'center'},
		{prop: 'name', label: 'License', align: 'center'}
	],
	loadServerPortQuery: { //下拉框加载数据请求参数
		page: 1,
		size: 50,
		licenseId: null,
	},
	more: true,
	securityGroupList: []
})

onMounted(() => {
	getDomainNameBindInfo()
	getDataList()
	getLicenseList()
	getLicenseAuthList()
	getProtocalList()
	fetchSecurityGroupList()
})


const columns = ref([
	{
		title: 'id',
		key: 'id',
		dataIndex: 'id',
		ellipsis: true,
	},
	{
		title: '用户名',
		key: 'userName',
		dataIndex: 'userName',
		ellipsis: true,
	},
	{
		title: 'licenseName',
		key: 'licenseName',
		dataIndex: 'licenseName',
		ellipsis: true,
	},
	{
		title: '协议',
		key: 'protocal',
		dataIndex: 'protocal',
		ellipsis: true,
	},
	{
		title: '域',
		key: 'domain',
		dataIndex: 'domain',
		ellipsis: true,
	},
	{
		title: '端口号',
		key: 'serverPort',
		dataIndex: 'serverPort',
		ellipsis: true,
	},
	{
		title: '客户端IP',
		key: 'clientIp',
		dataIndex: 'clientIp',
		ellipsis: true,
	},
	{
		title: '客户端端口',
		key: 'clientPort',
		dataIndex: 'clientPort',
		ellipsis: true,
	},
	{
		title: '限速',
		key: 'upLimitRate',
		dataIndex: 'upLimitRate',
		ellipsis: true,
	},
	{
		title: '描述',
		key: 'description',
		dataIndex: 'description',
		ellipsis: true,
	},
	{
		title: '修改时间',
		key: 'updateTime',
		dataIndex: 'updateTime',
		ellipsis: true,
	},
	{
		title: '启停状态',
		key: 'enable',
		dataIndex: 'enable',
		ellipsis: true,
		mapping: [
			{
				key: '1',
				value: '启用'
			},
			{
				key: '2',
				value: '停用'
			}
		]
	},
	{
		title: '上线状态',
		key: 'isOnline',
		dataIndex: 'isOnline',
		ellipsis: true,
		mapping: [
			{
				key: '1',
				value: '在线'
			},
			{
				key: '2',
				value: '离线'
			}
		]
	},
	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 260,
		fixed: 'right',
		buttonList: [
			{
				click: (field, record) => {
					handleOpenWebPage(record)
				},
				render: (record) => {
					return record.protocal === 'HTTP' || record.protocal === 'HTTP(S)' ? "OpenWebPage" : null;
				}
			},
			{
				type: "primary",
				click: (field, record) => {
					handleUpdate(record)
				},
				render: (record) => {
					return "编辑";
				}
			},
			{
				click: (field, record) => {
					handleModifyStatus(record, record.enable == 1 ? 2 : 1);
				},
				render: (record) => {
					return record.enable == 1 ? "停用" : "启用";
				}
			},

			{
				click: (field, record) => {
					handleDelete(record)
				},
				render: (record) => {
					return "删除";
				}
			}
		]
	}
])

const getList = async () => {
	let res = await portMappingApi.fetchList(config.value.listQuery);
	// this.list = response.records
	// this.total = response.total
	// this.listLoading = false
	return res;
}
const getDataList = async () => {
	const loginName = tool.data.get('USER_INFO').account;
	let response = await userApi.userSelector();
	config.value.userList = response.records
	const curUser = config.value.userList.find((val) => val.account === loginName)
	if (curUser) {
		config.value.listQuery.userId = curUser.id
	}
}
const fetchSecurityGroupList = async () => {
	let res = await securityGroupApi.fetchGroupList();
	config.value.securityGroupList = res;
}
const getDomainNameBindInfo = async () => {
	let response = await domainApi.domainNameBindInfo();
	config.value.domainName = response
}
const getAvailablePortList = (licenseId) => {
	config.value.loadServerPortQuery.licenseId = licenseId;
	config.value.serverPortList = []; //清掉数据
}
const getAllUserList = async () => {
	let response = await userApi.userSelector();
	config.value.userList = response.records
}
const getLicenseList = async () => {
	let response = await licenseApi.licenseList();
	config.value.licenseList = response
}
const getProtocalList = async () => {
	let response = await protocalApi.protocalList();
	config.value.protocalList = response
}
const getLicenseAuthList = async () => {
	let response = await licenseApi.licenseAuthList();
	config.value.licenseAuthList = response
}
const handleModifyStatus = async (row, enable) => {
	await portMappingApi.updateEnableStatus(row.id, enable);
	tableRef.value.refresh()
}
const openPort=()=>{
	window.open("https://lavm-console.jdcloud.com/lavm/detail/cn-east-1/lavm-ru3a8baeu6");
	window.open("https://116.198.243.213:27403/firewall");

}
const resetTemp = () => {
	config.value.temp = {
		id: undefined,
		licenseId: undefined,
		licenseName: undefined,
		serverPort: undefined,
		clientIp: '127.0.0.1',
		clientPort: undefined,
		userId: undefined,
		proxyResponses: undefined,
		proxyTimeoutMs: undefined
	}
	config.value.serverPortList = []
	config.value.loadServerPortQuery.licenseId = null;
	config.value.more = true;
}
const handleCreate =
	() => {
		resetTemp()
		config.value.dialogStatus = 'create'
		config.value.dialogFormVisible = true
	}
const createData = async () => {
	await portMappingApi.createUserPortMapping(config.value.temp);
	config.value.dialogFormVisible = false
	tableRef.value.refresh()
}

const handleOpenWebPage = (row) => {
	let url = location.protocol + '//' + location.hostname + ':' + row.serverPort
	if (row.domain) {
		url = location.protocol + '//' + row.domain
	}
	open(url)
}
const handleUpdate = (row) => {
	config.value.temp = Object.assign({}, row) // copy obj
	if (row.securityGroupId === 0) {
		config.value.temp.securityGroupId = null
	}
	config.value.temp.timestamp = new Date(config.value.temp.timestamp)
	config.value.dialogStatus = 'update'
	config.value.dialogFormVisible = true
	getAvailablePortList(row.licenseId)
}


const saveData = async () => {
	let b = await dataForm.value.validate();
	if (!b) {
		return
	}
	if (config.value.dialogStatus == 'create') {
		await createData();
	} else {
		await updateData();
	}

}
const updateData = async () => {
	const tempData = Object.assign({}, config.value.temp)
	await portMappingApi.updateUserPortMapping(tempData);
	config.value.dialogFormVisible = false
	tableRef.value.refresh()
}
const selectedFeeItem = (row) => {
	getAvailablePortList(row)
	config.value.temp.serverPort = null
}
const handleDelete = async (row) => {
	await portMappingApi.deletePortMapping(row.id);

	tableRef.value.refresh()

}
// 传入给load-select组件的函数
const loadServerPort = ({page = 1, more = false, keyword = ""} = {}) => {
	if (config.value.loadServerPortQuery.licenseId == null || config.value.loadServerPortQuery.licenseId == '') {
		config.value.more = false;
		message.info('请先选择License')
		return;
	}
	return new Promise(async resolve => {
		config.value.loadServerPortQuery.page = page;
		config.value.loadServerPortQuery.keyword = keyword;
		// 访问后端接口API
		let result = await portPoolApi.availablePortList(config.value.loadServerPortQuery);
		if (more) {
			config.value.serverPortList = [...config.value.serverPortList, ...result.records];
		} else {
			config.value.serverPortList = result.records;
		}

		// this.loadServerPortQuery.page = result.data.current;
		let {total, current, size} = result;
		config.value.more = page * size < total;
		config.value.loadServerPortQuery.page = current;
		resolve();
	});
}
</script>
